package cc.yihy.spider;

import lombok.Setter;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.monitor.SpiderMonitor;
import us.codecraft.webmagic.scheduler.MonitorableScheduler;

import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicInteger;


@Component
public class SpiderHealthIndicator implements HealthIndicator {

    @Setter
    private Spider spider;


    @Override
    public Health health() {

        if (spider == null) {
            return new Health.Builder().down().build();
        }


        Status status;

        switch (spider.getStatus()) {
            case Init:
            case Running:
                status = Status.UP;
                break;
            case Stopped:
                status = Status.UP;
                break;
            default:
                status = Status.UNKNOWN;
        }
        Health.Builder builder = new Health.Builder(status);

        builder.withDetail("threadAlive", spider.getThreadAlive());
        builder.withDetail("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(spider.getStartTime()));

        builder.withDetail("name", spider.getUUID());
        builder.withDetail("status", spider.getStatus());


        //        spider.start();
//        spider.stop();
//        spider.getThreadAlive();
//        spider.getStartTime();
//        spider.getPageCount();
//        spider.getUUID();
//        spider.getStatus();
//
        if (spider.getScheduler() instanceof MonitorableScheduler) {
            MonitorableScheduler scheduler = (MonitorableScheduler) spider.getScheduler();
            int leftRequestsCount = scheduler.getLeftRequestsCount(spider);
            int totalRequestsCount = scheduler.getTotalRequestsCount(spider);
            builder.withDetail("totalRequestsCount", totalRequestsCount);
            builder.withDetail("leftRequestsCount", leftRequestsCount);

        }

        SpiderMonitor.MonitorSpiderListener spiderListener = (SpiderMonitor.MonitorSpiderListener) spider.getSpiderListeners().get(0);
        AtomicInteger errorCount = spiderListener.getErrorCount();
        AtomicInteger successCount = spiderListener.getSuccessCount();

        builder.withDetail("pageCount", spider.getPageCount());
        builder.withDetail("successCount", successCount);
        builder.withDetail("errorCount", errorCount);


        return builder.build();
    }
}
